package com.mac.service;

import com.mac.mapper.UserMapper;
import com.mac.pojo.PageBean;
import com.mac.pojo.User;
import com.mac.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;

public class UserService {

    // 定义日志对象
    private static final Logger LOGGER = LoggerFactory.getLogger("UserService.Class");
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();


    public User ifUserExists(String username) {
        SqlSession sqlSession = factory.openSession();

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        try {
            User user = userMapper.ifUserExists(username);
            LOGGER.info("ifUserExists(username) -> succeed");
            sqlSession.close();
            return user;
        } catch (Exception e) {
            LOGGER.error("ifUserExists(username) -> failed",e);
            sqlSession.close();
            throw new RuntimeException(e);
        }

    }

    public User checkUser(String username, String password) {
        SqlSession sqlSession = factory.openSession();

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        User user;
        try {
            user =  userMapper.checkUser(username, password);
            LOGGER.info("checkUser(username, password) -> succeed");
            sqlSession.close();
            return user;
        } catch (Exception e) {
            LOGGER.error("checkUser(username, password) -> failed",e);
            sqlSession.close();
            throw new RuntimeException(e);
        }
    }

    public boolean addUser(User user) {
        SqlSession sqlSession = factory.openSession();

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        User u = userMapper.ifUserExists(user.getUsername());

        if (u == null){
            try {
                userMapper.addUser(user);
                sqlSession.commit();
                LOGGER.info("addUser(user) -> succeed");
                sqlSession.close();
            } catch (Exception e) {
                LOGGER.error("addUser(user) -> failed",e);
                sqlSession.close();
                throw new RuntimeException(e);
            }
        }
        return u == null;
    }

    public boolean deleteUser(String username) {
        SqlSession sqlSession = factory.openSession();

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        try {
            userMapper.deleteUser(username);
            sqlSession.commit();
            LOGGER.info("deleteUser(username) -> 成功");
            sqlSession.close();
            return true;
        } catch (Exception e) {
            LOGGER.error("deleteUser(username) -> 失败");
            sqlSession.close();
            return false;
        }
    }

    public boolean changeUserInfo(User user) {
        SqlSession sqlSession = factory.openSession();

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        try {
            userMapper.changeUserInfo(user);
            sqlSession.commit();
            LOGGER.info("changeUserInfo(user) -> 成功");
            sqlSession.close();
            return true;
        } catch (Exception e) {
            LOGGER.error("changeUserInfo(user) -> 失败",e);
            sqlSession.close();
            return false;
        }
    }

    public User selectByUserId(int userId){
        SqlSession sqlSession = factory.openSession();

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        try {
            User user = userMapper.selectByUserId(userId);
            LOGGER.info("selectByUserId(userId) -> 成功");
            sqlSession.close();
            return user;
        } catch (Exception e) {
            LOGGER.error("selectByUserId(userId) -> 失败",e);
            sqlSession.close();
            throw new RuntimeException(e);
        }
    }
    public User checkTelephone(String telephone){
        SqlSession sqlSession = factory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user;
        try {
            user = userMapper.checkTelephone(telephone);
            LOGGER.info("checkTelephone(telephone) -> succeed");
            sqlSession.close();
            return user;
        } catch (Exception e) {
            LOGGER.error("checkTelephone(telephone) -> failed",e);
            sqlSession.close();
            throw new RuntimeException(e);
        }
    }
    public User selectByUsername(String username){
        SqlSession sqlSession = factory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user;
        try {
            user=userMapper.selectByUsername(username);
            LOGGER.info("selectByUsername(username) -> succeed");
            sqlSession.close();
            return user;
        } catch (Exception e) {
            LOGGER.error("selectByUsername(username) -> failed",e);
            sqlSession.close();
            throw new RuntimeException(e);
        }
    }

    public ArrayList<User> selectAll() {
        SqlSession sqlSession = factory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        ArrayList<User> users;
        try {
            users = userMapper.selectAll();
            LOGGER.info("userMapper.selectAll() -> succeed");
            sqlSession.close();
            return users;
        } catch (Exception e) {
            LOGGER.error("userMapper.selectAll() -> failed",e);
            sqlSession.close();
            throw new RuntimeException(e);
        }
    }

    public boolean deleteByIds(int[] ids) {
        SqlSession sqlSession = factory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        try {
            userMapper.deleteByIds(ids);
            sqlSession.commit();
            sqlSession.close();
            LOGGER.info("userMapper.deleteByIds(ids) -> succeed");
            return true;
        } catch (Exception e) {
            LOGGER.error("userMapper.deleteByIds(ids) -> failed",e);
            sqlSession.close();
            throw new RuntimeException(e);
        }
    }

    public PageBean<User> selectByPage(int currentPage, int pageSize) {

        //4. 计算开始索引
        int begin = (currentPage - 1) * pageSize;
        // 计算查询条目数
        int size = pageSize;

        SqlSession sqlSession = factory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        ArrayList<User> users;
        try {
            users = userMapper.selectByPage(begin,size);

            //6. 查询总记录数
            int totalCount = userMapper.selectTotalCount();

            //7. 封装PageBean对象
            PageBean<User> pageBean = new PageBean<>();
            pageBean.setRows(users);
            pageBean.setTotalCount(totalCount);

            LOGGER.info("userMapper.selectByPage(begin,size) -> succeed");
            sqlSession.close();
            return pageBean;
        } catch (Exception e) {
            LOGGER.error("userMapper.selectByPage(begin,size) -> failed",e);
            sqlSession.close();
            throw new RuntimeException(e);
        }
    }

    public Integer selectTotalCount() {
        SqlSession sqlSession = factory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        Integer total;
        try {
            total = userMapper.selectTotalCount();
            LOGGER.info("userMapper.selectTotalCount() -> succeed");
            sqlSession.close();
            return total;
        } catch (Exception e) {
            LOGGER.error("userMapper.selectTotalCount() -> failed",e);
            sqlSession.close();
            throw new RuntimeException(e);
        }
    }

    public PageBean<User> selectByPageAndCondition(int currentPage, int pageSize, User user) {

        int begin = (currentPage - 1) * pageSize;
        // 计算查询条目数
        int size = pageSize;

        SqlSession sqlSession = factory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        ArrayList<User> users;
        try {
            users = userMapper.selectByPageAndCondition(begin,size,user);


            //6. 查询总记录数
            int totalCount = userMapper.selectTotalCountByCondition(user);

            //7. 封装PageBean对象
            PageBean<User> pageBean = new PageBean<>();
            pageBean.setRows(users);
            pageBean.setTotalCount(totalCount);

            LOGGER.info("selectByPageAndCondition(begin,size,user) -> succeed");
            sqlSession.close();
            return pageBean;
        } catch (Exception e) {
            LOGGER.error("selectByPageAndCondition(begin,size,user) -> failed",e);
            sqlSession.close();
            throw new RuntimeException(e);
        }
    }

    public Integer selectTotalCountByCondition(User user) {
        SqlSession sqlSession = factory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        Integer total;
        try {
            total = userMapper.selectTotalCountByCondition(user);
            LOGGER.info("userMapper.selectTotalCountByCondition(user) -> succeed");
            sqlSession.close();
            return total;
        } catch (Exception e) {
            LOGGER.error("userMapper.selectTotalCountByCondition(user) -> failed",e);
            sqlSession.close();
            throw new RuntimeException(e);
        }
    }
}
